// 穿越火线 CF首图 详情图生成
import { imgUrlToAttr } from "../../api/gameConfig/gameDictionary";
import {
  getURLBase64Image,
  loadImages,
  drawImagesAreaBg,
  drawBgBorder,
} from "./getUrlImg";
import {setPageImgArr,drawTextWithEllipsis} from "./common"

// 穿越火线 CF 首图
export async function makeTitleImgCF(data, list, attrs) {
  //console.log("%c Line:6 🍒 data", "color:#b03734", data);
  return new Promise(async (resolve, reject) => {
    // 取出已选择项
    let arr = [];
    let beforeArr = []
    let sm = "";
    list = list.split(",");
    if (!list || list == []) {
      reject("多选不能为空");
    }
    if (list && list.length) {
      attrs.forEach(async (item1) => {
        if (
          item1.fieldType == "checkbox" &&
          item1.isEnable === "0" &&
          item1.childAttributes &&
          item1.childAttributes.length
        ) {
          item1.childAttributes.forEach(async (item2) => {
            if (list.indexOf(String(item2.id)) > -1) {
              if(item2.sort<=-10000){
                beforeArr.push(item2)
              }else if(item1.aavName!='f19'){
                arr.push(item2);
              }
            }
          });
        }
      });
    }
    beforeArr
    console.log("%c Line:44 🍌 beforeArr", "color:#b03734", beforeArr);
    arr = beforeArr.concat(arr)
    try {
      const mainBg = await getURLBase64Image(
        "https://imgage.maimaihao.com/makeImg/CF/cfMainImgBgnew.png"
      );
      //console.log("%c Line:40 🥝 mainBg", "color:#4fff4B", mainBg);
      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");
      canvas.width = mainBg.width;
      canvas.height = mainBg.height;
      context.drawImage(mainBg, 0, 0, mainBg.width, mainBg.height);
      context.fillStyle = "#ffffff";
      context.font = "bold 50px Adobe Ming Std";
      // 头部标题 店铺名
      context.fillText(
        `${data.gameName || "--"}`,
        2560 / 2 - (data.gameName.length * 48) / 2,
        70
      );
      // 左侧展示
      context.font = "bold 38px Adobe Ming Std";
      context.fillText(`V武器数: ${data.f8 || "--"}`, 145, 380);
      context.fillText(`英雄角色: ${data.f11 || "--"}`, 145, 505);
      context.fillText(`语音包:${data.f2 ? data.f2 : "--"}`, 145, 627);
      context.fillText(`王者武器:${data.f9 ? data.f9 : "--"}`, 145, 761);
      context.fillText(`光效:${data.f1 ? data.f1 : "--"}`, 145, 886);
      context.fillText(`玩偶:${data.f7 ? data.f7 : "--"}`, 145, 1011);
      //  加载皮肤图片
      context.fillStyle = "#fff";
      
      let skinImgs = [];
      if (arr && arr.length) {
        try {
          // 不在七牛云的图片  传给服务端进行上传
        let notQiniu = []
        arr.forEach(r=>{
          if(r.imgUrl&&!r.imgUrl.includes('imgage.maimaihao.com')){
            notQiniu.push({
              id:r.id,
              imgUrl:r.imgUrl
            })
          }
        })
        if(notQiniu&&notQiniu.length){
          console.log("%c Line:89 🥟 notQiniu", "color:#6ec1c2", notQiniu);
         const attrImgList = await imgUrlToAttr(notQiniu)
          if(attrImgList.data&&attrImgList.data.length){
            attrImgList.data.forEach(r2=>{
              arr.forEach((r,i)=>{
                if(r.id==r2.id){
                  arr[i].imgUrl = r2.imgUrl
                }
              })
            })
          }
        }
        } catch (error) {
          
        }
        skinImgs = await loadImages(arr, 30);
      } else {
        // 没有Sren
      }
      // .sort(sortBy("sort"))
      let instances = skinImgs.length ? skinImgs : [];

      if (instances && instances.length) {
        let img15 = instances.splice(0, 30);
        // 开始绘制
        // startX,startY,rowNum,borderImg,imgWidth1,imgHeight,stepY,stepX
        // 下载背景图
        let bg1 = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/CF/cfskinbg1.png"
        );
        let bg2 = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/CF/cfskinbg2.png"
        );
        let bg3 = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/CF/cfskinbg3.png"
        );
        let bg4 = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/CF/cfskinbg4.png"
        );
        let defaultSkinbg = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/CF/cfskinbgdefault.png"
        );

        let opts = {
          startX: 690,
          startY: 200,
          rowNum: 6,
          stepY: 23,
          stepX: 30,
          txtLineHeight: 45,
          // imgWidth1: 328,
          // imgHeight: 174,
          imgWidth1: 265,
          imgHeight: 140,
          bgImgs: [bg1, bg2, bg3, bg4],
          defaultSkinbg:defaultSkinbg,
          gameId:6
        };
        context.font = "28px Adobe Ming Std";
        // context.fillStyle = "#333";
        drawImagesAreaBg(context, img15, opts);
        // 绘制结束
        const base64Url = canvas.toDataURL("image/jpeg", 0.8);
        resolve(base64Url);
      } else {
        const base64Url = canvas.toDataURL("image/jpeg", 0.8);
        resolve(base64Url);
      }
    } catch (error) {
      reject(error);
    }
  });
}
// 生成详情图-穿越火线 CF 多图
export async function makeDetailImgCF(data, skins, attrs) {
  return new Promise(async (resolve, reject) => {
    // 遍历所有皮肤  将没有图片的属性图片上传到后台
    for (let i = 0; i < skins.length; i++) {
      // 遍历不同类型的皮肤
      const typeMap = skins[i];
      if (typeMap.list.length > 0) {
        // typeMap.list.sort((a, b) => Number(a.kz1||0) - Number(b.kz1||0));
        let notQiniu = []
        for (let j = 0; j < typeMap.list.length; j++) {
          // 遍历到皮肤
          let skin = typeMap.list[j];
          // 不在七牛云的图片  传给服务端进行上传
          if(skin.imgUrl&&!skin.imgUrl.includes('imgage.maimaihao.com')){
            notQiniu.push({
              id:skin.id,
              imgUrl:skin.imgUrl
            })
          }
        }
        if(notQiniu&&notQiniu.length){
          const attrImgList = await imgUrlToAttr(notQiniu)
           if(attrImgList.data&&attrImgList.data.length){
             attrImgList.data.forEach(r8=>{
              typeMap.list.forEach((r7,h)=>{
                 if(r7.id==r8.id){
                  typeMap.list[h].imgUrl = r8.imgUrl
                 }
               })
             })
           }
        }
      }
    }

    
    // 分页数据
    let {opts,imgPageArr} = await setPageImgArr(skins,{
      headHeight:660,
      gameId:6
    })
    // // 定义一个整体图片的数组
    // let imgPageArr = [];
    // let commonIndex = 0; //定义一个全局的皮肤数
    // let imgNUm = -1; //图片页数  数量
    // let typeArrNum = -1; //每页图的分组数量
    
    // // 双重循环 遍历所有皮肤  将图片分页
    // for (let i = 0; i < skins.length; i++) {
    //   // 遍历不同类型的皮肤
    //   const typeMap = skins[i];
    //   if (typeMap.list.length > 0) {
    //     for (let j = 0; j < typeMap.list.length; j++) {
    //       // 遍历到皮肤
    //       let skin = typeMap.list[j];
    //       // 本次遍历不绘制  只将每张图片的内容区分开
    //       if (commonIndex === 0) {
    //         typeArrNum = -1;
    //         imgPageArr = [[]];
    //         imgPageArr[0].push({
    //           typeName: typeMap.name,
    //           skins: [],
    //         });
    //         imgNUm++;
    //         typeArrNum++;
    //       }
    //       if (commonIndex % 70 == 0 && commonIndex != 0) {
    //         typeArrNum = -1;
    //         imgPageArr.push([]);
    //         imgPageArr[imgNUm + 1].push({
    //           typeName: typeMap.name,
    //           skins: [],
    //         });
    //         imgNUm++;
    //         typeArrNum++;
    //       } //每张图片展示70个皮肤

    //       if (j == 0 && commonIndex % 70 != 0) {
    //         // 分组开始  在分页中创建分组数组
    //         imgPageArr[imgNUm].push({
    //           typeName: typeMap.name,
    //           skins: [],
    //         });
    //         typeArrNum++;
    //       }
    //       if (skin.imgUrl) {
    //         imgPageArr[imgNUm][typeArrNum].skins.push(skin);
    //       } else {
    //         typeMap.list.splice(j, 1);
    //         j--;
    //         continue;
    //       }
    //       commonIndex++;
    //     }
    //   }
    // }

    

    // 下载背景图
    let bg1 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/CF/cfskinbg1.png"
    );
    let bg2 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/CF/cfskinbg2.png"
    );
    let bg3 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/CF/cfskinbg3.png"
    );
    let bg4 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/CF/cfskinbg4.png"
    );
    let defaultSkinbg = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/CF/cfskinbgdefault.png"
    );

    // 绘制图片
    let imgsArr = [];
    if (imgPageArr && imgPageArr.length) {
      for (let k = 0; k < imgPageArr.length; k++) {
        let base64Img = await makeDetailImgCFOne(imgPageArr[k], data, [
          bg1,
          bg2,
          bg3,
          bg4
        ],defaultSkinbg);
        imgsArr.push(JSON.stringify(base64Img));
        if (k == imgPageArr.length - 1) {
          resolve(imgsArr);
        }
      }
    }
  });
}
// 绘制一个 穿越火线 CF 详情图
async function makeDetailImgCFOne(typeArr, data, bgImgs,defaultSkinbg) {
  ////console.log("%c Line:203 🍌 typeArr", "color:#93c0a4", typeArr);
  // 先计算当前页图片的高度
  let lineHeight = 160;
  let skinHeight = 0;
  let lineNum = 0;
  let skinNum = 0;
  if (typeArr && typeArr.length) {
    for (let i = 0; i < typeArr.length; i++) {
      let typeMap = typeArr[i];
      lineNum = lineNum + Math.ceil(typeMap.skins.length / 7);
      for (let j = 0; j < typeArr[i].skins.length; j++) {
        let url = typeArr[i].skins[j].imgUrl;
        if (url) {
          try {
            skinNum++;
            const temp = await getURLBase64Image(url);
            typeArr[i].skins[j].image = temp;
          } catch (error) {}
        } else {
          typeArr[i].skins.splice(j, 1);
          j--;
        }
      }
    }
  }
  skinHeight = Math.ceil(lineNum * lineHeight) + typeArr.length * 60 + 100 + 80; //所有皮肤 包括分类标题的高度  页尾距离
  //console.log("%c Line:217 🍪 skinHeight", "color:#fca650", skinHeight);

  // 开始创建画布
  let y = 140; //图的绘制时距离上端的距离
  let x = 47; //绘制皮肤时的x距离
  // 创建canvas实例
  const canvas = document.createElement("canvas");
  canvas.style.background = "#ffffff";
  const context = canvas.getContext("2d");
  canvas.width = 1500;
  canvas.height = Math.ceil(skinHeight);
  context.font = "40px Adobe Ming Std";
  // 下载分类名称背景
  let typeNameBg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/CF/cf-subtitle-bg.png"
  );
  // 下载主背景
  let mainBgImg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/CF/cf-bg.png"
  );
  // 下载头部背景
  let titleBg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/CF/cf-titlebg.png"
  );
  // 下载右上角装饰
  let hpjyrg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/heping/hpjyrg.png"
  );
  // 开始绘制

  // 绘制背景图
  context.drawImage(mainBgImg, 0, 0, canvas.width, canvas.height);
  // 绘制标题背景
  context.drawImage(titleBg, 0, 0, canvas.width, 100);
  // 填充标题文字
  context.font = "bold 30px Adobe Ming Std";
  context.fillStyle = "#fff"; // 文字填充颜色
  // 头部标题 店铺名
  context.fillText(
    `${data.gameName || "--"}`,
    canvas.width / 2 - (data.gameName.length * 30) / 2,
    50
  );
  // 绘制右上角装饰 hpjyrg
  context.drawImage(hpjyrg, 1482, 130, 5, 68);
  // 绘制主要区域的背景
  drawBgBorder(context, 30, 130, canvas.width - 60, skinHeight - 150, {
    radius: 12,
    borderWidth: 2,
    startColor: "rgba(59, 65, 68, 0.6)",
    endColor: "rgba(20, 22, 21, 0.6)",
    borderColor: "#909090",
  });

  //
  // 开始绘制皮肤
  if (typeArr && typeArr.length) {
    for (let i = 0; i < typeArr.length; i++) {
      let typeMap = typeArr[i];
      for (let j = 0; j < typeMap.skins.length; j++) {
        let skin = typeMap.skins[j];
        if (j == 0) {
          // 分组开始  先绘制分类标题图片和分类名
          if (i != 0) {
            y += lineHeight;
          }
          context.drawImage(typeNameBg, 0, y - 100, 337, 229);
          context.font = "28px Adobe Ming Std";
          context.fillStyle = "#ffffff"; // 文字填充颜色
          let name = typeMap.typeName || "其他";
          // let txtWidth = name.length * 28;
          context.fillText(` ${name}`, 60, y + 25);
          y += 60;
          x = 47;
        }
        if (j % 7 == 0 && j != 0) {
          x = 47;
          y += lineHeight;
        }
        // 绘制每张图中的皮肤
        if (skin.image) {
          // 绘制背景图
          if (skin.kz1 && (bgImgs[skin.kz1 - 1] || bgImgs[skin.kz1 - 1] == 0)) {
            const bg = bgImgs[skin.kz1 - 1];
            // console.log("%c Line:223 🌭 bg", "color:#f5ce50", bg);
            context.drawImage(bg, x, y, 184, 100);
          }else{
            if(defaultSkinbg){
              context.drawImage(defaultSkinbg, x, y, 184, 100);
            }
          }
          context.drawImage(skin.image, x + 10, y + 10, 164, 80);
          context.fillStyle = "#fff"; // 文字填充颜色
          context.font = "20px Adobe Ming Std";
          let name = skin.fieldName ? skin.fieldName : "未知"
          if(skin.kz2){
            name = `(${skin.kz2})${name}`
          }

          drawTextWithEllipsis(context,name, x, y + 130,200)
          x += 204;
        }
      }
    }
  }
  return canvas.toDataURL("image/jpeg", 0.8);
}
